package com.ypf.demo_ssm.interceptor;

import com.ypf.demo_ssm.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;


/**
 * 注册拦截器
 */
@Slf4j
@Component // 将其放入ioc容器中
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, String> map=new HashMap<>();
        //从http请求头获取token
        String token = request.getHeader("token");
        if (token == null) {
            throw new RuntimeException("No token found");
        }
        if (!new JwtUtils().validateToken(token)) {
            throw new RuntimeException("Token invalid");
        }
        return true;
    }
}